package com.campus.controller;

import com.campus.common.JwtUtil;
import com.campus.dto.LoginDto;
import com.campus.model.User;
import com.campus.service.UserService;
import com.campus.web.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseResult<?> login(@RequestBody LoginDto loginDto) {
        String loginName = loginDto.getLoginName();
        String password = loginDto.getPassword();

        // 验证登录
        boolean isValidLogin = userService.validateLogin(loginName, password);

        if (isValidLogin) {
            // 如果登录成功，获取角色ID并生成JWT Token
            Optional<User> userOptional = userService.getUserByLoginName(loginName);
            User user = userOptional.get();  // 获取用户信息
            Optional<Integer> roleId = userService.getRoleIdByUserId(user.getId());  // 获取角色ID

            // 如果角色存在，生成Token
            if (roleId.isPresent()) {
                String token = JwtUtil.generateToken(loginName, roleId.get());

                // 将生成的 token 更新到数据库中的 t_sys_user 表
                userService.updateUserToken(user.getId(), token);  // 调用 service 层更新 token

                return ResponseResult.ok(Map.of("token", token), "Login successful");
            }
        }
        return ResponseResult.error(HttpStatus.UNAUTHORIZED, "Invalid username or password");
    }

    @GetMapping("/get-login-name")
    public ResponseResult<?> getLoginNameByToken(@RequestParam String token) {
        Optional<String> loginName = userService.getLoginNameByToken(token);
        if (loginName.isPresent()) {
            return ResponseResult.ok(Map.of("loginName", loginName.get()), "Login name fetched successfully");
        } else {
            return ResponseResult.error(HttpStatus.NOT_FOUND, "Token not found");
        }
    }

}
